from django.shortcuts import render

# Create your views here.
from rest_framework.viewsets import GenericViewSet,ModelViewSet
from rest_framework.response import Response
from rest_framework.decorators import list_route
from rest_framework import permissions
from django.utils.timezone import datetime,timedelta
from .filters import UserFilter
from .serializer import *


class AccountsGenericViewSet(GenericViewSet):
    serializer_class = RegCodeSerializers
    @list_route(methods=["POST"])
    def get_code(self,request):
        serializer=RegCodeSerializers(data=request.data)
        serializer.is_valid(raise_exception=True)
        return Response(serializer.data)

    @list_route(methods=['POST'])
    def reg(self,request):
        serializer=NewUserSerializers(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response('ok')

    @list_route(methods=['POST'])
    def login(self, request):
        serializer=UserLoginSerializer(data=request.data,context=locals())
        serializer.is_valid(raise_exception=True)
        return Response(serializer.data)


class AddressViewSet(ModelViewSet):
    queryset = Address.objects.all()   #查询数据源
    serializer_class = AddressSerializer   #指定序列化器
    permission_classes = (permissions.IsAuthenticated,)
    filter_backends = (UserFilter,)


class CheckInViewSet(ModelViewSet):
    queryset = CheckIn.objects.all()   #查询数据源
    serializer_class = CheckInSerializer   #指定序列化器
    permission_classes = (permissions.IsAuthenticated,)
    filter_backends = (UserFilter,)

    def create(self, request, *args, **kwargs):
        count = None
        check_in, is_create = CheckIn.objects.get_or_create(user=request.user)

        if not check_in.datetime:
            count = 0

        elif check_in.datetime.date() == datetime.now().date():
            pass

        elif check_in.datetime.date() != datetime.now().date() - timedelta(days=1):
            count = 0

        elif check_in.datetime.date() == datetime.now().date() - timedelta(days=1):
            count = check_in.count

        if not None is count:
            check_in.count = count
            check_in.count += 1
            check_in.datetime = datetime.now()
            check_in.save()

        return Response(0)